<template>
  <PageWrapDrawer :show="show" :isUpdate="props.isUpdate" :title="title" title-suffix="菜单"
  width="65%"
  @success="onSubmit" 
  @on-drawer-close="onClose">
    <Form name="basic"
          :model="insideData.data"
          :label-col="{ span: 6 }"
          :wrapper-col="{ span: 18 }"
          autocomplete="off"
          layout="horizontal"
    >
    <Card hoverable :bordered="false" size="small">
      <template #title><h3 class="card-title">| 路由信息</h3></template>
      <Row>
        <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
          <FormItem label="内部名称" name="name" v-bind="validateInfos['data.name']">
            <a-input v-model:value="insideData.data.name"/>
          </FormItem>
        </Col>
        <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
          <FormItem label="路径" name="path" v-bind="validateInfos['data.path']">
            <a-input v-model:value="insideData.data.path"/>
          </FormItem>
        </Col>
        <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
          <FormItem label="组件" name="component" v-bind="validateInfos['data.component']">
            <a-input v-model:value="insideData.data.component"/>
          </FormItem>
        </Col>
        <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
          <FormItem label="重定向" name="redirect">
            <a-input v-model:value="insideData.data.redirect"/>
          </FormItem>
        </Col>
        <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
          <FormItem label="父菜单" name="parentId">
            <!-- <InputNumber v-model:value="insideData.data.parentId" :min="0" style="width: 200px;"
            :formatter="value => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')"
            :parser="value => value.replace(/\$\s?|(,*)/g, '')"/> -->
            <TreeSelect v-model:value="insideData.data.parentId" placeholder="请选择"
              style="width: 100%"
              allow-clear
              tree-default-expand-all
              :fieldNames="{value: 'ID', label: 'title2', children: 'children'}"
              :tree-data="treeDataOfMenu"
              :get-popup-container="(tn) => tn.parentNode"
            >
            </TreeSelect>
          </FormItem>
        </Col>
        <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
          <FormItem label="顺序" name="sort">
            <InputNumber v-model:value="insideData.data.sort" :min="0" :max="9999" style="width: 100%"/>
          </FormItem>
        </Col>
        <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" :xxl="24">
          <FormItem label="系统按钮" name="buttonList"
          :label-col="{ xs: {span: 6}, sm: {span: 6}, md: {span: 6}, lg: {span: 6}, xl: {span: 3}, xxl: {span: 3} }"
          :wrapper-col="{ xs: {span: 18}, sm: {span: 18}, md: {span: 18}, lg: {span: 18}, xl: {span: 21}, xxl: {span: 21} }"
          >
            <Select v-model:value="insideData.data.bidList" mode="tags" allowClear placeholder="请选择"
            :options="selecteListOfButton"
            :get-popup-container="(tn) => tn.parentNode"/>
          </FormItem>
        </Col>
      </Row>
    </Card>

    <Card hoverable :bordered="false" size="small">
      <template #title><h3 class="card-title">| 元信息</h3></template>
      <Row>
        <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
          <FormItem label="标题" name="title" v-bind="validateInfos['data.meta.title']">
            <a-input v-model:value="insideData.data.meta.title"/>
          </FormItem>
        </Col>
        <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
          <FormItem label="图标" name="icon">
            <a-input v-model:value="insideData.data.meta.icon">
              <template #suffix>
                <Icon :icon="insideData.data.meta.icon" />
              </template>
              <template #addonAfter>
                <a v-bind:href="iconHref" target="_blank" title="选择图标"><AimOutlined/></a>
              </template>
            </a-input>
          </FormItem>
        </Col>
        <!-- <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
          <FormItem label="顺序" name="orderNo">
            <InputNumber v-model:value="insideData.data.meta.orderNo" :min="0" :max="999" style="width: 100%"/>
          </FormItem>
        </Col> -->
        <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
          <FormItem label="菜单" name="hideMenu">
            <RadioGroup v-model:value="insideData.data.meta.hideMenu">
              <Radio :value="false">显示</Radio>
              <Radio :value="true">隐藏</Radio>
            </RadioGroup>
          </FormItem>
        </Col>
        <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
          <FormItem label="面包屑" name="hideChildrenInMenu">
            <RadioGroup v-model:value="insideData.data.meta.hideChildrenInMenu">
              <Radio :value="false">显示</Radio>
              <Radio :value="true">隐藏</Radio>
            </RadioGroup>
          </FormItem>
        </Col>
        <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
          <FormItem label="Tab图钉" name="affix">
            <RadioGroup v-model:value="insideData.data.meta.affix">
              <Radio :value="true">固定</Radio>
              <Radio :value="false">不固定</Radio>
            </RadioGroup>
          </FormItem>
        </Col>
        <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
          <FormItem label="Tab" name="affix">
            <RadioGroup v-model:value="insideData.data.meta.hideTab">
              <Radio :value="false">显示</Radio>
              <Radio :value="true">隐藏</Radio>
            </RadioGroup>
          </FormItem>
        </Col>
        <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
          <FormItem label="链接" name="isLink">
            <RadioGroup v-model:value="insideData.data.meta.isLink">
              <Radio :value="true">是</Radio>
              <Radio :value="false">否</Radio>
            </RadioGroup>
          </FormItem>
        </Col>
        <Col :xs="24" :sm="24" :md="24" :lg="24" :xl="12" :xxl="12">
          <FormItem label="Iframe" name="frameSrc">
            <a-input v-model:value="insideData.data.meta.frameSrc"/>
          </FormItem>
        </Col>
      </Row>
    </Card>
    </Form>
  </PageWrapDrawer>
</template>
<script lang="ts" name="menuDrawer" setup>
import { AimOutlined } from "@ant-design/icons-vue";
import type { TreeSelectProps } from 'ant-design-vue';
import {
Card, Col, Form, FormItem, InputNumber, Radio, RadioGroup, Row, Select, SelectProps, TreeSelect
} from 'ant-design-vue';
import { groupBy } from 'lodash-es';
import { computed, reactive, ref, toRaw, watchPostEffect } from 'vue';
import { getListData as getButtonListData } from '/@/api/admin/button';
import { create, getListData as getMenuListData, update } from '/@/api/admin/menu';
import { Icon, } from '/@/components/Icon/index';
import { PageWrapDrawer } from '/@/components/PageWrapDrawer';
import { useI18n } from '/@/hooks/web/useI18n';
import { useMessage } from '/@/hooks/web/useMessage';
import { iconSelect, } from '/@/utils/my';

// https://blog.csdn.net/qq_49327308/article/details/124467691
const {
      createMessage,
    } = useMessage();
    const {info, success, warning, error} = createMessage;

const emit = defineEmits(['on-success', 'on-drawer-close'])
const props = defineProps({
    show: Boolean,
    isUpdate: Boolean,
    isCopy: Boolean,
    row: {type: [Object, null] as PropType<Object | null>, default: null,},
})

const useForm = Form.useForm;
const insideData = reactive({
  data: {
    ID: null,
    name: '',
    path: '',
    component: '',
    redirect: '',
    parentId: null,
    metaId: 0,
    sort: 0,
    buttonList: [],
    bidList: [], // 新增和更新时，存放按钮ID的辅助字段
    meta: {
      ID: null,
      title: '',
      icon: '',
      orderNo: 0,
      hideMenu: false,
      hideChildrenInMenu: false,
      affix: false,
      hideTab: false,
      isLink: false,
      frameSrc: '',
    },
  }
});

const title = ref('')
watchPostEffect(() => {
  if (props.show && props.isCopy) {
    title.value = '复制并创建 客户'
  }
})

const selecteListOfButton = ref<SelectProps['options']>([]);
const treeDataOfMenu = ref<TreeSelectProps['treeData']>([])
watchPostEffect(() => {
  if (props.show && props.isCopy) {
    title.value = '复制并创建 菜单'
  }

  let v1 = props.row as any
  if (v1) {
    insideData.data = {...v1}
    if (!v1.parentId) insideData.data.parentId = null
    insideData.data.bidList = v1.buttonList && v1.buttonList.map((e:any) => e.ID) || []
  }
  if (props.show) {
    getButtonListData().then(dd => {
      let list = dd.map((e:any) => {
        let group = ''
        switch (e?.place) {
          case 0: group = '表格-左上'; break;
          case 1: group = '表格-右上'; break;
          case 2: group = '表格内-操作';break;
          case 3: group = '其他'; break;
        }
        return {label: e.name, value: e.ID, group: group}
      })
      let groupby = groupBy(list, 'group')
      let newArr = [] as any[]
      Object.keys(groupby).forEach(key => newArr.push({label: key, options: groupby[key] }))
      selecteListOfButton.value = newArr
    })
    getMenuListData().then(dd => {
      treeDataOfMenu.value = deep(dd)
    })
  }
})
function deep(parent:any[]) {
  const { t } = useI18n();
  parent.forEach(e => {
    if (e.meta) {
      e.title2 = t(e.meta.title)
    }
    if (e.children && e.children.length > 0) deep(e.children)
  })
  return parent
}

const iconHref = computed(() => {
  return iconSelect(insideData.data.meta.icon)
})

const rulesRef = reactive({
  'data.name': [
    {required: true, message: '请输入内部名称',},
  ],
  'data.path': [
    {required: true, message: '请输入路径',},
  ],
  'data.component': [
    {required: true, message: '请输入组件',},
  ],
  'data.meta.title': [
    {required: true, message: '请输入标题'}
  ]
});
const {resetFields, validate, validateInfos} = useForm(insideData, rulesRef, {
  onValidate: (...args) => {
    // console.log('args=>', ...args)
  },
});

const onSubmit = () => {
  validate()
    .then(async () => {
      let params = toRaw(insideData.data)
      if (props.isUpdate) {
        await update(params).then(() => {
          onClose()
        })
      } else {
        await create(params).then(() => {
          onClose()
        })
      }
      emit('on-success')
    })
}

const onClose = () => {
  Object.assign(insideData, {data: {meta: {}}});
  resetFields();
  emit('on-drawer-close');
};

</script>
<style scoped>
.card-title{
  /* opacity: .75; */
  color: #f90;
}
:deep().ant-card:not(:last-child){
  margin-bottom: 12px;
}
</style>
